<template>
  <div class="tw-libsetinfo">
    <el-form
      ref="reRegisterForm"
      :model="req"
      :rules="rules"
      label-width="90px"
      class="xsetinfo"
    >
      <el-form-item label="姓名:" prop="realName">
        <el-input
          v-model="req.user.realName"
          label-position="left"
          placeholder="请输入姓名"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="账户姓名:" prop="loginName">
        <el-input
          v-model="req.user.loginName"
          label-position="left"
          disabled
        >
        </el-input>
      </el-form-item>
      <el-form-item label="性别:" class="is-required">
        <el-select v-model="req.user.sex" placeholder="请选择性别">
          <el-option label="男" value="0"></el-option>
          <el-option label="女" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱:" prop="loginEmail">
        <el-input
          v-model="req.user.loginEmail"
          label-position="left"
          placeholder="请填写邮箱"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="手机号:" prop="loginMobile">
        <el-input
          v-model="req.user.loginMobile"
          label-position="left"
          placeholder="请输入手机号"
        >
        </el-input>
      </el-form-item>
      <el-form-item class="xlicense" label="证件:" prop="cardType">
        <el-select v-model="req.user.cardType">
          <el-option
            v-for="(item, index) in licenseList" :key="index"
            :label="item.lable"
            :value="item.value">
          </el-option>
        </el-select>
        <el-input
          class="xwt-input"
          v-model="req.user.idCardNo"
          label-position="left"
          placeholder="请输入证件号"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="用户头像:" prop="avatar">
          <div class="twui-astable xupload xsamll" v-if="!reUpload">
            <div class="twui-imgzoombox twui-astable-col xupload-objbox">
              <div class="twui-imgzoom" :class="{xzoom:isZoom}" @click="isZoom=!isZoom">
                <img v-if="req.user.facePicture" :src="imageUrl" />
                <img v-else src="@assets/nav-pic-headportrait.png">
              </div>
            </div>
          </div>
          <imgUploadAndView @fileUrlChange="fileUrlChange"></imgUploadAndView>
        </el-form-item>

      <el-form-item>
        <button
          type="button"
          class="twui-btn xmain xlarge xsebtn"
          @click.prevent="submitForm('reRegisterForm')">保存
        </button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import props from './props'
import style from '../tw-lib-base/style'
import imgUploadAndView from './tw-img-uploadAndView'

export default {
  name: 'tw-libset-info',

  props,

  mixins: [style],

  components: {
    imgUploadAndView
  },

  data() {

    var validatePhone = (rule, value, callback) => {
      let reg = /(^$)|^1[345789]\d{9}$/;
      if (reg.test(this.req.user.loginMobile) || this.req.user.loginMobile === undefined) {
        callback()
      } else {
        callback(new Error('请输入正确的手机号'))
      }
    }

    var validateIdCardNo = (rule, value, callback) => {
      if (this.req.user.idCardNo) {
        var reg = /^[0-9a-zA-Z]+$/;
        if (!reg.test(this.req.user.idCardNo)) {
          callback(
            new Error("证件号码格式不正确")
          );
        } else {
          callback();
        }
      } else {
        callback();
      }
    }

    var validateLoginName = (rule, value, callback) => {
      let realNameReq = /[`~!#$%^&*()\-+=<>?:"{}|,/;'\\[\]~！#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im;
      if (/\s+/.test(this.req.user.realName)) {
        callback(
          new Error("姓名不能包含空格")
        );
      } else if (this.req.user.realName.length === 0) {
        callback(
          new Error("账户名不能为空")
        );
      } else if (this.req.user.realName.length < 2 || this.req.user.realName.length > 32) {
        callback(
          new Error("姓名长度不能小于2位或者大于32位")
        );
      } else if (realNameReq.test(this.req.user.realName)) {
        callback(
          new Error("您输入了非法字符")
        );
      } else {
        callback();
      }
    }
    var validEmail = (rule, value, callback) => {
      let reg = /(^$)|^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (reg.test(this.req.user.loginEmail) || this.req.user.loginEmail === undefined) {
        callback()
      } else {
        callback(new Error('请输入正确的邮箱'))
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error("请输入密码"))
      } else {
        if (this.req.staticPassword !== '') {
          this.$refs.registerForm.validateField('staticPasswordR')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error("请再次输入密码"))
      } else if (value !== this.req.staticPassword) {
        callback(new Error("两次输入的密码不一致!"))
      } else {
        callback()
      }
    }

    return {
      req: {
        code: '',
        roleId: '1000000008',
        staticPasswordR: '',
        staticPassword: '',
        user: {
          userid: '',
          loginName: '',
          loginEmail: '',
          loginMobile: '',
          staticPassword: '',
          realName: '',
          status: '',
          facePicture: '',
          sex: '',
          cardType: '',
          idCardNo: ''
        },
        developer: {
          companyName: '',
          businessLicenseNumber: '',
          businessLicensePhoto: ''
        }
      },

      rules: {
        staticPassword: [{ required: true, validator: validatePass, trigger: 'blur' }],
        staticPasswordR: [{ required: true, validator: validatePass2, trigger: 'blur' }],
        loginMobile: [{
          validator: validatePhone,
          trigger: 'blur'
        }],
        idCardNo: [{
          validator: validateIdCardNo,
          trigger: 'blur'
        }],
        realName: [{
          validator: validateLoginName,
          required: true,
          trigger: 'blur'
        }],
        loginEmail: [{
          validator: validEmail,
          trigger: 'blur' }]
      },

      // formData: {
      //   name: '',
      //   accountname: 'admin',
      //   gender: '',
      //   mailbox: '',
      //   phone: '',
      //   licenseTypes: '1',
      //   license: '',
      //   facePicture: ''
      // },
      licenseList: [
        {lable: '居民身份证', value: '1'},
        {lable: '军官证', value: '2'},
        {lable: '士兵证', value: '3'},
        {lable: '文职干部证', value: '4'},
        {lable: '部队离退休证', value: '5'},
        {lable: '香港特区护照/身份证明', value: '6'},
        {lable: '澳门特区护照/身份证明', value: '7'},
        {lable: '台湾居民来往大陆通行证', value: '8'},
        {lable: '境外永久居住证', value: '9'},
        {lable: '护照', value: 'A'},
        {lable: '户口薄', value: 'B'},
        {lable: '其它', value: 'Z'}
      ],
      reUpload: false,
      isZoom: false
    }
  },

  computed: {

    imageUrl: function () {
      return this.$twApp.gateway + '/fs/media' + this.req.user.facePicture
    },

    style() {
      return {
        elformWidth: this.elformWidth,
        setToUrl: this.setToUrl,
        themeColor: this.themeColor,
        themeColorHover: this.themeColorHover,
        selectBorderColor: this.selectBorderColor
      }
    }
  },

  methods: {
    fileUrlChange: function (val) {
      this.reUpload = true
      this.req.user.facePicture = val
    },

    setStyle() {
      let style = `
        ::root.tw-libsetinfo .el-form.xsetinfo {
          width: ${this.elformWidth}
        }

        .twui-btn.xmain.xlarge.xsebtn {
          background: ${this.themeColor};
          border-color: ${this.themeColor}
        }

        .twui-btn.xmain.xlarge.xsebtn:hover {
          background: ${this.themeColorHover};
          border-color: ${this.themeColorHover}
        }

        .el-input__inner:focus,
        .el-select .el-input.is-focus .el-input__inner {
          border-color: ${this.selectBorderColor};
        }
      `

      this.addStyle(style)
    },
    /**
     * 功能: 提交表单
     * @param {String} type : 1-注册 2-找回密码
     *
     */
    submitForm (formName) {
      let vm = this
      let req = { 'entity': { 'userId': vm.req.user.userId, 'facePicture': vm.req.user.facePicture, 'realName': vm.req.user.realName, 'loginName': vm.req.user.loginName, 'sex': vm.req.user.sex, 'loginEmail': vm.req.user.loginEmail, 'loginMobile': vm.req.user.loginMobile, 'idCardNo': vm.req.user.idCardNo, 'cardType': vm.req.user.cardType } }
      vm.$refs[formName].validate((valid) => {
        if (valid) {
          window.axios.post( this.$twApp.gateway + '/openapi-uc/uc/updateUser', req)
            .then(function (response) {
              if (response.data.serverResult.resultCode === '200') {
                // utils.set('CURRENT_FACE_PICTURE', vm.req.user.facePicture)
                // utils.set('CURRENT_LOGIN_NAME', vm.req.user.realName)
                vm.$message({
                  message: '修改个人信息成功！',
                  type: 'success'
                })

                window.$twApp.user.realName = vm.req.user.realName
                window.$twApp.user.facePicture = vm.req.user.facePicture
                window.localStorage.setItem(window.$twApp.user.userId, JSON.stringify(window.$twApp.user))

                // 修改成功2秒转跳
                if (vm.setToUrl) {
                  window.setTimeout(function() {
                    window.location.href = vm.setToUrl
                  }, 2000);
                }
              } else {
                vm.$message({
                  message: response.data.serverResult.resultMessage,
                  type: 'error'
                })
              }
            }).catch(function (error) {
              vm.$message.error('修改个人信息存在错误! 可能电话号码或邮箱已存在。')
              console.log(error)
            })
        } else {
          console.log(req)
          vm.$message({
            message: '校验不通过，请检查表单！',
            type: 'error'
          })
          return false
        }
      })
    }
  },

  mounted() {
    // this.login()
    this.setStyle()
  },

  watch: {},

  created () {
    var vm = this
    window.axios.post( this.$twApp.gateway + '/openapi-uc/uc/getUserBaseInfo', null)
      .then(function (response) {
        vm.req.user = response.data.responseEntity.user
        vm.req.org = response.data.responseEntity.org
        vm.req.developer = response.data.responseEntity.developer
      })
      .catch(function (error) {
        vm.$message({
          message: error.data.serverResult.resultMessage,
          type: 'error'
        })
        console.log(error)
      })
  }
}
</script>

<style lang="scss">
@import './css/index.scss';
</style>
